# @Time    : 2022/2/10 19:40
# @Author  : junbaibai
# @File    : save_node_service.py
import typing

from src.db.obj.save_node import SaveNode
from src.utils.sqlite3utils import dbUtil
from src.utils.logger import Logger

logger = Logger(__name__)


def node_exists(hoi: SaveNode):
    statements = f"""select id from save_node 
    where date='{hoi.date}' and src_path='{hoi.src_path}' 
    order by update_time desc limit 1"""
    with dbUtil.execute(statements) as c:

        logger.i(c.fetchone())


def last_node(src_path) -> SaveNode:
    statements = f"""
        select {",".join(SaveNode.__slots__)}
        from save_node
        where src_path='{src_path}'
        order by update_time desc limit 1
    """
    with dbUtil.execute(statements) as c:

        res = c.fetchone()
        return SaveNode(res)


def insert_node(hoi: SaveNode):
    dbUtil.insert(hoi.table_name, hoi.normal_field, hoi.normal_field_value)


def update_node_time(hoi: SaveNode) -> bool:
    statements = f"""
        update save_node
        set update_time={hoi.update_time}
        where id={hoi.id}
    """
    logger.i(statements)
    try:
        with dbUtil.execute(statements) as c:
            return True
    except Exception as e:
        logger.e(e)
        return False


def listening_files() -> list:
    statements = f"""
        select src_path from save_node
        group by src_path
    """
    with dbUtil.execute(statements) as c:
        return c.fetchall()


def listening_file_record(src_path) -> typing.Generator[SaveNode, None, None]:
    statements = f"""
        select {",".join(SaveNode.__slots__)}
        from save_node
        where src_path='{src_path}'
        order by id asc
    """
    logger.i(statements)
    with dbUtil.execute(statements) as c:
        res = c.fetchall()
        nodes = (SaveNode(i) for i in res)
        nodes = {node.id: [node, []] for node in nodes}
        for key, value in nodes.items():
            node: SaveNode = value[0]
            parent = nodes.get(node.parent)
            if parent is not None:
                parent[1].append(node.id)
        for key, value in nodes.items():
            node: SaveNode = value[0]
            children: list = value[1]

            def a(n: SaveNode, child_list: list):
                yield n
                for i in child_list:
                    item = nodes.get(i)
                    for j in a(item[0], item[1]):
                        yield j

            return a(node, children)
